<?php
// 第一步：处理AJAX请求 - 必须在任何其他逻辑之前处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // 禁用错误显示以避免HTML输出污染JSON响应
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(E_ALL);
    
    // 启动会话
    session_start();
    
    // 导入数据库连接和认证
    require_once 'database.php';
    require_once 'common/auth.php';
    
    // 清除所有输出缓冲
    while (ob_get_level()) {
        ob_end_clean();
    }
    header('Content-Type: application/json; charset=utf-8');
    
    // 检查用户是否已登录
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => '用户未登录']);
        exit();
    }
    
    // 检查用户权限
    $user_id = $_SESSION['user_id'];
    $user_roles = getUserRoles($user_id);
    
    if (!in_array('考试项目管理员', $user_roles)) {
        echo json_encode(['success' => false, 'message' => '权限不足，仅考试项目管理员可以访问此页面']);
        exit();
    }
    
    // 获取考试项目ID
    $exam_id = isset($_POST['exam_id']) ? intval($_POST['exam_id']) : 0;
    if ($exam_id <= 0) {
        echo json_encode(['success' => false, 'message' => '无效的考试项目ID']);
        exit();
    }
    
    if ($_POST['action'] === 'save_data') {
        try {
            // 详细日志：显示接收到的POST数据
            $log_file = __DIR__ . '/debug.log';
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 接收到的POST数据: " . print_r($_POST, true) . "\n", FILE_APPEND);
            
            $sessions_data = json_decode($_POST['sessions_data'], true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                $error_msg = 'JSON解析错误: ' . json_last_error_msg();
                file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] $error_msg\n", FILE_APPEND);
                echo json_encode(['success' => false, 'message' => $error_msg]);
                exit();
            }
            
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 解析后的sessions_data: " . print_r($sessions_data, true) . "\n", FILE_APPEND);
        
        // 删除现有数据
        $delete_sql = "DELETE FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $exam_id);
        $delete_result = $delete_stmt->execute();
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 删除现有数据结果: " . ($delete_result ? '成功' : '失败') . "\n", FILE_APPEND);
        
        // 插入新数据 - 修正字段名以匹配数据库表结构
        $insert_sql = "INSERT INTO arrange_examination_rooms_and_invigilators 
                      (exam_id, session_number, subject_name, exam_date, start_time, end_time,
                       room_type, total_rooms_no_backup, room_numbering_pattern, students_per_room,
                       invigilators_per_room, backup_rooms_needed) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insert_stmt = $conn->prepare($insert_sql);
        
        if (!$insert_stmt) {
            $error_msg = "预处理语句准备失败: " . $conn->error;
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] $error_msg\n", FILE_APPEND);
            throw new Exception($error_msg);
        }
        
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 准备执行的SQL: $insert_sql\n", FILE_APPEND);
        
        foreach ($sessions_data as $index => $session) {
            // 详细日志：显示每条数据的内容和绑定参数
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 准备插入第" . ($index + 1) . "条数据: " . print_r($session, true) . "\n", FILE_APPEND);
            
            // 记录绑定参数的具体值
            $bind_params = [
                'exam_id' => $exam_id,
                'session_number' => $session['session_number'],
                'subject_name' => $session['subject_name'],
                'exam_date' => $session['session_date'],
                'start_time' => $session['start_time'],
                'end_time' => $session['end_time'],
                'room_type' => $session['room_type'],
                'total_rooms_no_backup' => $session['rooms_needed_without_backup'],
                'room_numbering_pattern' => $session['room_number_pattern'],
                'students_per_room' => $session['candidates_per_room'],
                'invigilators_per_room' => $session['invigilators_per_room'],
                'backup_rooms_needed' => $session['backup_rooms_count']
            ];
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 绑定参数值: " . print_r($bind_params, true) . "\n", FILE_APPEND);
            
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 绑定参数类型字符串: iisssssiiiii (12个参数)\n", FILE_APPEND);
            
            // 将参数值赋给变量以确保通过引用传递
            $exam_id_val = $exam_id;
            $session_number_val = $session['session_number'];
            $subject_name_val = $session['subject_name'];
            $exam_date_val = $session['session_date'];
            $start_time_val = $session['start_time'];
            $end_time_val = $session['end_time'];
            $room_type_val = $session['room_type'];
            $total_rooms_no_backup_val = $session['rooms_needed_without_backup'];
            $room_numbering_pattern_val = $session['room_number_pattern'];
            $students_per_room_val = $session['candidates_per_room'];
            $invigilators_per_room_val = $session['invigilators_per_room'];
            $backup_rooms_needed_val = $session['backup_rooms_count'];
            
            $bind_result = $insert_stmt->bind_param("iisssssiiiii", 
                $exam_id_val,
                $session_number_val,
                $subject_name_val,
                $exam_date_val,
                $start_time_val,
                $end_time_val,
                $room_type_val,
                $total_rooms_no_backup_val,
                $room_numbering_pattern_val,
                $students_per_room_val,
                $invigilators_per_room_val,
                $backup_rooms_needed_val
            );
            
            if (!$bind_result) {
                $error_msg = "绑定参数失败: " . $insert_stmt->error;
                file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] $error_msg\n", FILE_APPEND);
                throw new Exception($error_msg);
            }
            
            $execute_result = $insert_stmt->execute();
            if (!$execute_result) {
                $error_msg = "插入第" . ($index + 1) . "条数据失败: " . $insert_stmt->error;
                file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] $error_msg\n", FILE_APPEND);
                // 记录最后一次错误信息
                file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] 数据库错误: " . $conn->error . "\n", FILE_APPEND);
                throw new Exception($error_msg);
            }
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [DEBUG] 第" . ($index + 1) . "条数据插入成功，影响行数: " . $insert_stmt->affected_rows . "\n", FILE_APPEND);
        }
        
        $success_msg = '数据保存成功，共保存 ' . count($sessions_data) . ' 条记录';
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [SUCCESS] $success_msg\n", FILE_APPEND);
        echo json_encode(['success' => true, 'message' => $success_msg]);
        
        } catch (Exception $e) {
            $error_message = '保存失败: ' . $e->getMessage();
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] 捕获异常: " . $error_message . "\n", FILE_APPEND);
            file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] [ERROR] 异常堆栈: " . $e->getTraceAsString() . "\n", FILE_APPEND);
            echo json_encode(['success' => false, 'message' => $error_message]);
        }
        exit();
    }
    
    if ($_POST['action'] === 'clear_data') {
        try {
            // 删除当前考试项目的所有场次数据
            $delete_sql = "DELETE FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param("i", $exam_id);
            $delete_stmt->execute();
            
            echo json_encode(['success' => true, 'message' => '数据清空成功']);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '清空失败：' . $e->getMessage()]);
        }
        exit();
    }
    
    // 如果没有匹配的action，返回错误
    echo json_encode(['success' => false, 'message' => '未知的操作类型']);
    exit();
}

// 非AJAX请求的页面初始化
// 确保只有非AJAX请求才会执行以下代码
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) {
    session_start();
    error_reporting(E_ALL);
    // 启用错误显示对于非AJAX请求
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    
    // 引用统一导航栏
    include_once 'common/navigation.php';
    
    // 导入数据库连接
    require_once 'database.php';
    require_once 'common/auth.php';
    
    // 检查用户是否已登录
    if (!isset($_SESSION['user_id'])) {
        header('Location: index.php');
        exit();
    }
    
    // 检查用户权限
    $user_id = $_SESSION['user_id'];
    $user_roles = getUserRoles($user_id);
    
    if (!in_array('考试项目管理员', $user_roles)) {
        echo "<script>alert('权限不足，仅考试项目管理员可以访问此页面。'); window.history.back();</script>";
        exit();
    }

// 获取传入的考试项目ID
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
if ($exam_id <= 0) {
    echo "<script>alert('无效的考试项目ID。'); window.history.back();</script>";
    exit();
}

// 获取考试项目信息
$sql = "SELECT exam_name FROM exams WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();
$exam_info = $result->fetch_assoc();

if (!$exam_info) {
    echo "<script>alert('未找到指定的考试项目。'); window.history.back();</script>";
    exit();
}

// 显示错误消息
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']); // 清除错误消息
}

$all_rooms = [];
try {
    $rooms_sql = "SELECT * FROM examination_rooms ORDER BY building_number, floor_number, room_number";
    $rooms_result = $conn->query($rooms_sql);
    $all_rooms = $rooms_result->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    error_log("获取课室信息失败: " . $e->getMessage());
}

// 获取备用考场
$backup_rooms = [];
try {
    $backup_sql = "SELECT * FROM examination_rooms WHERE purpose = '备用考场' ORDER BY building_number, floor_number, room_number";
    $backup_result = $conn->query($backup_sql);
    $backup_rooms = $backup_result->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    error_log("获取备用考场信息失败: " . $e->getMessage());
}

// 获取现有数据
$sql = "SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();
$existing_data = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编排考场及预编排监考员 - 里程碑1</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .main-content {
            margin: 20px 0;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        
        .page-header h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 300;
        }
        
        .milestone-nav {
            background-color: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        
        .debug-log {
            background-color: #1e1e1e;
            color: #00ff00;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #333;
        }
        
        .log-entry {
            margin: 2px 0;
            padding: 2px 0;
        }
        
        .log-time {
            color: #888;
            margin-right: 10px;
        }
        
        .log-level-info {
            color: #00ff00;
        }
        
        .log-level-error {
            color: #ff4444;
        }
        
        .log-level-warning {
            color: #ffaa00;
        }
        
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }
        
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
        }
        
        .form-control {
            border-radius: 4px;
        }
        
        .btn {
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <?php 
    // 直接调用renderNavigationBar()函数，该函数会自动输出导航栏
    // navigation.php文件被包含时会自动调用此函数
    ?>
    
    <div class="container-fluid">
        <div class="main-content">
            <div class="page-header">
                <h1><i class="fas fa-building"></i> 编排考场及预编排监考员</h1>
                <p class="mb-0">考试项目：<?php echo htmlspecialchars($exam_info['exam_name']); ?> - 里程碑1</p>
            </div>
            
            <!-- 错误消息显示 -->
            <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php endif; ?>
            
            <!-- 里程碑导航 -->
            <div class="milestone-nav">
                <div class="btn-group" role="group">
                    <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">里程碑1</a>
                    <a href="arrange_examination_rooms_milestone2.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-outline-secondary">里程碑2</a>
                    <a href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-outline-secondary">里程碑3</a>
                    <a href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-outline-secondary">里程碑4</a>
                    <a href="arrange_examination_rooms_milestone5.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-outline-secondary">里程碑5</a>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons mt-4 mb-4">
                <a href="edit_examination_data.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-success">
                    <i class="fas fa-edit"></i> 编辑考场数据
                </a>
                <button id="clearLogBtn" class="btn btn-secondary"><i class="fas fa-eraser"></i> 清空日志</button>
            </div>
            
            <!-- Debug日志显示区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-terminal"></i> Debug日志</h5>
                </div>
                <div class="card-body p-0">
                    <div id="debugLog" class="debug-log">
                        <div class="log-entry"><span class="log-time">[页面加载]</span><span class="log-level-info">Debug日志系统已启动</span></div>
                    </div>
                </div>
            </div>
            
            <!-- 考试场次数据表格 -->
            <div class="table-responsive">
                <table id="sessionsTable" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th width="6%">考试场次</th>
                            <th width="10%">本场次科目名称</th>
                            <th width="10%">本场次考试日期</th>
                            <th width="8%">本场次考试开始时间</th>
                            <th width="8%">本场次考试结束时间</th>
                            <th width="12%">本场次使用考场类型</th>
                            <th width="8%">本场次需要的考场总数（不含备用考场）</th>
                            <th width="10%">考场号编号规律</th>
                            <th width="8%">本场次每个考场的考生数量</th>
                            <th width="8%">本考试项目每个考场需要监考员数量</th>
                            <th width="8%">本项目需要的备用考场数量</th>
                            <th width="6%">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($existing_data)): ?>
                        <!-- 显示空表格示例 -->
                        <tr>
                            <td colspan="12" class="text-center text-muted">暂无数据，请点击"添加场次"按钮添加考试场次信息</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($existing_data as $row): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['session_number'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['subject_name'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['exam_date'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['start_time'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['end_time'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['room_type'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['total_rooms_no_backup'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['room_numbering_pattern'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['students_per_room'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['invigilators_per_room'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['backup_rooms_needed'] ?? ''); ?></td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="removeSession(this)">删除</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 添加场次 - 此功能已移至edit_examination_data.php
        // document.getElementById('addSessionBtn').addEventListener('click', function() {
        //     addLog('开始添加新场次', 'info');
        //     const tbody = document.querySelector('#sessionsTable tbody');
        //     const rowCount = tbody.rows.length;
        //     
        //     // 如果表格中有"暂无数据"的行，先清除
        //     if (rowCount === 1 && tbody.rows[0].cells.length === 1) {
        //         tbody.innerHTML = '';
        //     }
        //     
        //     const newRow = tbody.insertRow();
        //     newRow.innerHTML = `
        //         <td><input type="number" class="form-control form-control-sm" value="${tbody.rows.length + 1}" min="1"></td>
        //         <td><input type="text" class="form-control form-control-sm" placeholder="请输入科目名称"></td>
        //         <td><input type="date" class="form-control form-control-sm"></td>
        //         <td><input type="time" class="form-control form-control-sm"></td>
        //         <td><input type="time" class="form-control form-control-sm"></td>
        //         <td><select class="form-select form-select-sm">
        //             <option value="">请选择考场类型</option>
        //             <option value="学生课室">学生课室</option>
        //             <option value="实训室">实训室</option>
        //             <option value="电脑机房">电脑机房</option>
        //         </select></td>
        //         <td><input type="number" class="form-control form-control-sm" min="1" onchange="calculateRooms(this)"></td>
        //         <td><select class="form-select form-select-sm">
        //             <option value="">请选择编号规律</option>
        //             <option value="第X考场">第X考场 (如：第1考场、第2考场)</option>
        //             <option value="XX考场">XX考场 (如：01考场、02考场)</option>
        //             <option value="0XX考场">0XX考场 (如：001考场、002考场)</option>
        //             <option value="1XX考场">1XX考场 (如：101考场、102考场)</option>
        //             <option value="4460010XX考场">4460010XX考场 (如：446001001考场、446001002考场)</option>
        //         </select></td>
        //         <td><input type="number" class="form-control form-control-sm" value="30" min="1"></td>
        //         <td><select class="form-select form-select-sm">
        //             <option value="2">2</option>
        //             <option value="3">3</option>
        //         </select></td>
        //         <td><select class="form-select form-select-sm" onchange="showBackupRoomSelector(this)">
        //             <option value="0">0</option>
        //             <option value="1">1</option>
        //         </select></td>
        //         <td><button class="btn btn-sm btn-danger" onclick="removeSession(this)">删除</button></td>
        //     `;
        // });
        // addLog(`成功添加场次 ${tbody.rows.length}`, 'info');
        //
        // 根据编号规律生成考场号
        function generateRoomNumbers(pattern, totalRooms) {
            const roomNumbers = [];
            
            for (let i = 1; i <= totalRooms; i++) {
                let roomNumber = '';
                
                switch (pattern) {
                    case '第X考场':
                        roomNumber = `第${i}考场`;
                        break;
                    case 'XX考场':
                        roomNumber = `${i.toString().padStart(2, '0')}考场`;
                        break;
                    case '0XX考场':
                        roomNumber = `${i.toString().padStart(3, '0')}考场`;
                        break;
                    case '1XX考场':
                        roomNumber = `${(100 + i)}考场`;
                        break;
                    case '4460010XX考场':
                        roomNumber = `${44600100 + i}考场`;
                        break;
                    default:
                        roomNumber = `考场${i}`;
                }
                
                roomNumbers.push(roomNumber);
            }
            
            return roomNumbers;
        }
        
        // 计算考场并更新显示
        function calculateRooms(element) {
            const row = element.closest('tr');
            const totalRooms = parseInt(element.value) || 0;
            const patternSelect = row.cells[7].querySelector('select');
            const pattern = patternSelect.value;
            
            if (totalRooms > 0 && pattern) {
                const roomNumbers = generateRoomNumbers(pattern, totalRooms);
                addLog(`为场次生成了${totalRooms}个考场号: ${roomNumbers.join(', ')}`, 'info');
                
                // 可以在这里添加显示生成的考场号的逻辑
                // 例如在某个地方显示生成的考场号列表
            }
        }
        
        // 显示备用考场选择器
        function showBackupRoomSelector(element) {
            const row = element.closest('tr');
            const backupValue = element.value;
            
            // 移除已存在的备用考场选择器
            const existingSelector = row.querySelector('.backup-room-selector');
            if (existingSelector) {
                existingSelector.remove();
            }
            
            if (backupValue === '1') {
                // 创建备用考场选择器
                const backupSelector = document.createElement('div');
                backupSelector.className = 'backup-room-selector mt-2';
                backupSelector.innerHTML = `
                    <label class="form-label">选择备用考场：</label>
                    <select class="form-select form-select-sm" name="backup_room_id">
                        <option value="">请选择备用考场</option>
                        <?php foreach ($backup_rooms as $backup_room): ?>
                        <option value="<?php echo $backup_room['id']; ?>"><?php echo htmlspecialchars($backup_room['room_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                `;
                element.parentNode.appendChild(backupSelector);
            }
        }
        
        // 删除场次
        function removeSession(button) {
            const row = button.closest('tr');
            const sessionNumber = row.cells[0].querySelector('input') ? row.cells[0].querySelector('input').value : '未知';
            addLog(`删除场次 ${sessionNumber}`, 'warning');
            row.remove();
            
            // 重新编号场次
            updateSessionNumbers();
            
            // 如果删除后没有数据行，显示提示信息
            const tbody = document.querySelector('#sessionsTable tbody');
            if (tbody.rows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="text-center text-muted">暂无数据，请点击"添加场次"按钮添加考试场次信息</td></tr>';
            }
        }
        
        // 更新场次编号
        function updateSessionNumbers() {
            const tbody = document.querySelector('#sessionsTable tbody');
            const rows = tbody.querySelectorAll('tr');
            
            rows.forEach((row, index) => {
                if (row.cells.length > 1) { // 排除提示行
                    const sessionInput = row.cells[0].querySelector('input');
                    if (sessionInput) {
                        sessionInput.value = index + 1;
                    }
                }
            });
        }
        

        

        
        // Debug日志功能
        function addLog(message, level = 'info') {
            const debugLog = document.getElementById('debugLog');
            const now = new Date();
            const timeStr = now.toLocaleTimeString();
            
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `<span class="log-time">[${timeStr}]</span><span class="log-level-${level}">${message}</span>`;
            
            debugLog.appendChild(logEntry);
            debugLog.scrollTop = debugLog.scrollHeight;
        }
        
        // 清空日志按钮事件
        const clearLogBtn = document.getElementById('clearLogBtn');
        if (clearLogBtn) {
            clearLogBtn.addEventListener('click', function() {
                const debugLog = document.getElementById('debugLog');
                debugLog.innerHTML = '<div class="log-entry"><span class="log-time">[日志清空]</span><span class="log-level-info">Debug日志已清空</span></div>';
                addLog('日志系统重新启动', 'info');
            });
        }
        
        // 页面加载时检查是否需要显示备用考场选择器
        document.addEventListener('DOMContentLoaded', function() {
            addLog('页面DOM加载完成', 'info');
            
            // 为现有行绑定事件
            const tableRows = document.querySelectorAll('#sessionsTable tbody tr');
            if (tableRows.length > 0) {
                tableRows.forEach(row => {
                    if (row.cells.length > 1) {
                        const candidatesInput = row.cells[3].querySelector('input');
                        const seatsInput = row.cells[5].querySelector('input');
                        const backupInput = row.cells[7].querySelector('input');
                        const backupSelect = row.cells[8].querySelector('select');
                        
                        if (candidatesInput) candidatesInput.addEventListener('change', function() { calculateRooms(this); });
                        if (seatsInput) seatsInput.addEventListener('change', function() { calculateRooms(this); });
                        if (backupInput) backupInput.addEventListener('change', function() { calculateTotal(this); });
                        if (backupSelect) backupSelect.addEventListener('change', function() { calculateTotal(this); });
                    }
                });
                addLog('现有表格行事件绑定完成', 'info');
            }
        });
    </script>
</body>
</html>
<?php } ?>